<?php /** 预约考试 api **/
require_once '../config/req.conf.php';
require_once '../utils/CommonMethods.php';
require_once '../utils/VerifyFormData.php';
require_once '../utils/DBUtils.php';

/* 1. 进行表单验证 */
if( !VerifyFormData::appointmentDataVerify($_POST) )return;

/* 2. 查询数据库: 证件号是否已被注册 */
DBUtils::init();
$sql = DBUtils::getSql("php_user")->where("uniqueID = '{$_POST['uniqueID']}'")->select();
$hasId = DBUtils::queryOne($sql);
if( !CommonMethods::isEmpty($hasId) ){
    $confirm = DBUtils::queryOne(
        DBUtils::getSql("php_user")
            ->where("uniqueID = '{$_POST['uniqueID']}' and username = '{$_POST['username']}'")
            ->select()
    );
    if( !CommonMethods::isEmpty($confirm) ){
        /* 判断当前账号是否预约成功 status: -1: 正在审核 0: 预约通过,可以查看密码 1: 预约通过,不能查看密码 */
        switch ($hasId['status']){
            case '-1':
                RespJson::fail("处于预约状态, 请等待审核通过", array('status' => $hasId['status']));
                break;
            case '0':
                DBUtils::execute(DBUtils::getSql("php_user")->set("status = 1")->where("uniqueID = '{$_POST['uniqueID']}'")->update());
                RespJson::fail("已通过预约, 初始密码为123456, 仅展示一次", array('status' => $hasId['status']));
                break;
            case '1':
                RespJson::fail("已经通过预约了", array('status' => $hasId['status']));
                break;
            default:
                RespJson::fail("系统管理员", array('status' => $hasId['status']));
                break;
        }
        return;
    }
    RespJson::fail("该证件号已存在, 请输入对应的正确姓名即可查询状态");
    return;
}

/* 3. 插入数据库: 注册一个考生 */
$success = DBUtils::execute("insert into php_user(uniqueID, username) values('{$_POST['uniqueID']}', '{$_POST['username']}')");
if( $success ){
    /* 进行权限分配 */
    $info = DBUtils::queryOne("select id from php_user where uniqueID = '{$_POST['uniqueID']}'");
    DBUtils::execute("insert into php_user_permission(uId, pId) values({$info['id']}, 2)");
    RespJson::fail("已提交预约申请, 请等待审核", array('status' => "success"));
    return;
}else{
    RespJson::fail("预约失败, 请重试", array('status' => "fail"));
    return;
}

